import { Injectable } from '@nestjs/common';
import { PostsEntity } from './posts.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ObjectType, CommonResponse } from 'src/types';
import { responseWrapper } from 'src/utils';

@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(PostsEntity)
    private readonly postsRepo: Repository<PostsEntity>,
  ) {}

  async create(data: ObjectType): Promise<PostsEntity> {
    const role = await this.postsRepo.create(data);
    return await this.postsRepo.save(role);
  }

  // 物理删除
  async deleteById(id: number): Promise<CommonResponse> {
    const {
      raw: { affectedRows },
    } = await this.postsRepo.delete(id);
    return responseWrapper(
      affectedRows ? '删除成功' : '删除失败',
      !affectedRows,
    );
  }

  // 更新数据
  async modifyById(id: number, data: ObjectType): Promise<CommonResponse> {
    const {
      raw: { affectedRows },
    } = await this.postsRepo.update(id, data);
    return responseWrapper(
      affectedRows ? '修改成功' : '修改失败',
      !affectedRows,
    );
  }

  // 用户列表
  async list(): Promise<any> {
    // 简单查询
    return await this.postsRepo.find();
  }

  async getById(id: number): Promise<PostsEntity> {
    return await this.postsRepo.findOne(id);
  }
}
